from cassacoproject.cassaco.models import Subcategory
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required
def new(request):
    subcat = Subcategory()
    subcat.description = request.POST['description']
    subcat.category_id = int(request.POST['category'])
    subcat.user = request.user
    subcat.save()
    return HttpResponse(subcat.id)
    
@login_required
def getHTMLSelect(request, category_id, id):
    subcategories = Subcategory.objects.filter(user=request.user, 
                                               category=category_id)
    output = '<select name="subcategory_id" id="subcategory"><option>--'
    output += '<option value="new">New sub-type...'
    for c in subcategories:
        selected = ''
        if c.id == int(id):
            selected = 'selected'
        output += '<option %s value="%d">%s' % (selected, c.id, c.description)
    output += '</select>'
    return HttpResponse(output)

@login_required
def delete(request, id):
    Subcategory.objects.get(id=int(id), user=request.user).delete()
    return HttpResponseRedirect('/cassaco')